//
//  AliyunOSSTool.m
//  DSJY
//
//  Created by lx on 17/6/26.
//  Copyright © 2017年 dsjy. All rights reserved.
//  阿里云的OSS

#import "AliyunOSSTool.h"
#import "MTConst.h"

@interface AliyunOSSTool ()
@property(nonatomic, strong) OSSClient *client;
@end

@implementation AliyunOSSTool

#pragma mark - 懒加载
//- (OSSClient *)client
//{
//    if (_client == nil) {
//        // 打开调试log
//        [OSSLog enableLog];
//        
//        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey secretKey:SecretKey];
//        
//        OSSClientConfiguration * conf = [OSSClientConfiguration new];
//        conf.maxRetryCount = 2;
//        conf.timeoutIntervalForRequest = 30;
//        conf.timeoutIntervalForResource = 24 * 60 * 60;
//        
//        _client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
//    }
//    return _client;
//}

#pragma mark - 系统回调
- (instancetype)init
{
    if (self = [super init]) {
        [self setupEnvironment];
    }
    return self;
}

//初始化
- (void)setupEnvironment
{
    // 打开调试log
    [OSSLog enableLog];
    
    // 初始化sdk
    [self initOSSClient];
}

- (void)initOSSClient
{
    // 打开调试log
    [OSSLog enableLog];
    
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey secretKey:SecretKey];
    
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 2;
    conf.timeoutIntervalForRequest = 30;
    conf.timeoutIntervalForResource = 24 * 60 * 60;
    
    self.client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
}

// 异步下载
- (OSSTask *)downloadObjectAsyncWithPath:(NSString *)path objectKey:(NSString *)objectKey
{
    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    // required
    request.bucketName = bucketName;
    request.objectKey = objectKey;//@"upload/course/110c40681edc4c179cd97fe6649a772f/Goodbye.1.mp3";
    
    //optional
    request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
        MTLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
    };
    request.downloadToFileURL = [NSURL fileURLWithPath:path];
    
    OSSTask *getTask = [self.client getObject:request];
    
    return getTask;
}

@end
